package com.example.vbloodbanksalesforce.service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import com.example.vbloodbanksalesforce.BaseActivity;

public class HttpUrlConnectionClass extends AsyncTask<String, Void, String> {

	private HttpURLConnection http_url_conn;
	BaseActivity mCaller;
	String response;
	
	public void attach(BaseActivity ui) {
		mCaller = ui;
	}

	public String insertData[];
	public HttpUrlConnectionClass(String data[]){
		if(data!=null){
		insertData = data;}
		
	}
	@Override
	protected String doInBackground(String... params) {
		// TODO Auto-generated method stub

		try {

			String url = params[0];
			String argument = params[1];
			URL w_Url = new URL(params[0]);
			http_url_conn = (HttpURLConnection) w_Url.openConnection();

			if (argument.equalsIgnoreCase("Login")) {
				

				getLogin();
			}
			if (argument.equalsIgnoreCase("insert")) {
				insertingData();
			}
			if (argument.equalsIgnoreCase("retrive")) {
				retriveingData();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	public String getLogin() {

		try {
			http_url_conn.setRequestMethod("POST");
			http_url_conn
					.setRequestProperty("Content-type", "application/json");

			Log.i("NCS",
					"Response code is  :" + http_url_conn.getResponseCode());
			Log.i("NCS",
					"Response Method is  :" + http_url_conn.getRequestMethod());
			Log.i("NCS",
					"Response Message is  :"
							+ http_url_conn.getResponseMessage());

			response = convert_To_String(http_url_conn.getInputStream());

			JSONObject jsonObject = new JSONObject(response);

			Session.sInstanceUrl = jsonObject.getString("instance_url");
			Session.sAccessToken = jsonObject.getString("access_token");

			Log.i("NCS", "InstanceUrl" + Session.sInstanceUrl);
			
			return response;
		} catch (Exception e) {
			Log.i("NCS","Exception is  :"+e.getMessage());
		}
		
		return null;
	}
	public String insertingData(){
		try {
			http_url_conn.setRequestMethod("POST");
			http_url_conn.setRequestProperty("Content-type", "application/json");
			http_url_conn.setRequestProperty("Authorization", "OAuth "+Session.sAccessToken);
			JSONObject jsonParam = new JSONObject();
			
			jsonParam.put("Name",insertData[0]);
			jsonParam.put("BloodGroup__c",insertData[1]);
			jsonParam.put("DonorAge__c",insertData[2]);
			jsonParam.put("DonarArea__c",insertData[3]);
			jsonParam.put("DonorPhoneNO__c",insertData[4]);
			jsonParam.put("EmailID__c",insertData[5]);        
			
			Log.i("NCS","JsonResponse   :"+jsonParam+"  :  "+jsonParam.toString());	
			          
			http_url_conn.setUseCaches (false);
			http_url_conn.setDoInput(true);
			http_url_conn.setDoOutput(true);

		      DataOutputStream wr = new DataOutputStream (
		    		  http_url_conn.getOutputStream ());
		      wr.writeBytes (jsonParam.toString());
		      wr.flush ();
		      wr.close ();
/*
		      //Get Response	           
		      InputStream is = http_url_conn.getInputStream();
		      BufferedReader rd = new BufferedReader(new InputStreamReader(is));
		      String line;
		      StringBuffer response = new StringBuffer(); 
		      while((line = rd.readLine()) != null) {
		        response.append(line);
		        response.append('\r');
		      }
		      rd.close();
		  
		
			
			
			Log.i("NCS","Response  is :"+ response.toString());
			res = response.toString();*/
		      Log.i("RGT","Response code is  :"+http_url_conn.getResponseCode());
				Log.i("RGT","Response Method is  :"+http_url_conn.getRequestMethod());
				Log.i("RGT","Response Message is  :"+http_url_conn.getResponseMessage());
		      response = convert_To_String(http_url_conn.getInputStream());
		      return response;
		      } catch (Exception e) {
			
			Log.i("NCS","Exception 2 is  :"+e.getMessage());	
			
		}
		return null;
		
	}
	
	public String retriveingData(){
		try {
			Log.i("NCS","AccessToken"+Session.sAccessToken);
		http_url_conn.setRequestMethod("GET");
		http_url_conn.setRequestProperty("Authorization", "OAuth "+Session.sAccessToken);
		
			Log.i("RGT","Response code is  :"+http_url_conn.getResponseCode());
			Log.i("RGT","Response Method is  :"+http_url_conn.getRequestMethod());
			Log.i("RGT","Response Message is  :"+http_url_conn.getResponseMessage());
			
			response = convert_To_String(http_url_conn.getInputStream());
			return response;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			
		}
		return null;
	}

	public static String convert_To_String(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {

				sb.append(line + "\n");
				Log.i("TPT", "Line is  :" + line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	@Override
	protected void onPostExecute(String result) {
		// TODO Auto-generated method stub
		mCaller.apiReturn(result);
		super.onPostExecute(result);
	}

}
